import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/features/gallery/screens/gallery_screen.dart';
import 'package:family_app/src/features/finance/screens/finance_screen.dart';
import 'package:family_app/src/features/finance/screens/home_screen.dart' as finance_home;
import 'package:family_app/src/features/secure_vault/screens/secure_vault_screen.dart';
import 'package:family_app/src/features/calendar/screens/calendar_screen.dart';
import 'package:family_app/src/features/family/screens/family_members_screen.dart';
import 'package:family_app/src/common/router.dart';
import 'package:family_app/src/theme/app_theme.dart';
import 'package:family_app/src/features/auth/providers/auth_provider.dart';
import 'package:family_app/src/features/family/providers/family_providers.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:family_app/src/common/constants.dart';

/// 首页
class HomeScreen extends ConsumerStatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  ConsumerState<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends ConsumerState<HomeScreen> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldKey,
      appBar: _buildAppBar(),
      drawer: _buildDrawer(),
      body: _buildBody(),
    );
  }
  
  // 构建AppBar
  AppBar _buildAppBar() {
    return AppBar(
      title: const Text('家庭助手'),
      leading: IconButton(
        icon: const Icon(Icons.menu),
        onPressed: () => _scaffoldKey.currentState?.openDrawer(),
      ),
      actions: [
        IconButton(
          icon: const Icon(Icons.notifications),
          onPressed: () {
            // 打开通知页面
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('通知页面开发中')),
            );
          },
        ),
        IconButton(
          icon: const Icon(Icons.settings),
          onPressed: () {
            // 打开设置页面
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('设置页面开发中')),
            );
          },
        ),
      ],
    );
  }
  
  // 构建抽屉
  Widget _buildDrawer() {
    return Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: [
          _buildDrawerHeader(),
          _buildDrawerItem(
            icon: Icons.people,
            title: '家庭成员管理',
            onTap: () => Navigator.pushNamed(context, AppRouter.family),
          ),
          _buildDrawerItem(
            icon: Icons.photo_album,
            title: '相册',
            onTap: () => _navigateTo(const GalleryScreen()),
          ),
          _buildDrawerItem(
            icon: Icons.account_balance_wallet,
            title: '财务管理',
            onTap: () => _navigateTo(const finance_home.HomeScreen()),
          ),
          _buildDrawerItem(
            icon: Icons.lock,
            title: '安全保险箱',
            onTap: () => _navigateTo(const SecureVaultScreen()),
          ),
          _buildDrawerItem(
            icon: Icons.calendar_today,
            title: '家庭日历',
            onTap: () => _navigateTo(const CalendarScreen()),
          ),
          _buildDrawerItem(
            icon: Icons.favorite,
            title: '关爱管理',
            onTap: () => _showFeatureUnderDevelopment('关爱管理'),
          ),
          _buildDrawerItem(
            icon: Icons.description,
            title: '文档管理',
            onTap: () => _showFeatureUnderDevelopment('文档管理'),
          ),
          _buildDrawerItem(
            icon: Icons.location_on,
            title: '位置共享',
            onTap: () => _showFeatureUnderDevelopment('位置共享'),
          ),
          const Divider(),
          _buildDrawerItem(
            icon: Icons.settings,
            title: '设置',
            onTap: () => _showFeatureUnderDevelopment('设置'),
          ),
          _buildDrawerItem(
            icon: Icons.logout,
            title: '退出登录',
            onTap: () => _showLogoutConfirmDialog(context),
          ),
        ],
      ),
    );
  }
  
  // 构建抽屉头部
  Widget _buildDrawerHeader() {
    return DrawerHeader(
      decoration: BoxDecoration(
        color: AppTheme.primaryColor,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          CircleAvatar(
            radius: 30.r,
            backgroundColor: Colors.white,
            child: Icon(
              Icons.person,
              size: 40.r,
              color: AppTheme.primaryColor,
            ),
          ),
          SizedBox(height: 10.h),
          const Text(
            '用户名',
            style: TextStyle(
              color: Colors.white,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 5.h),
          const Text(
            'user@example.com',
            style: TextStyle(
              color: Colors.white70,
              fontSize: 14,
            ),
          ),
        ],
      ),
    );
  }
  
  // 构建抽屉项
  Widget _buildDrawerItem({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
  }) {
    return ListTile(
      leading: Icon(icon),
      title: Text(title),
      onTap: () {
        Navigator.pop(context); // 关闭抽屉
        onTap();
      },
    );
  }
  
  // 构建主体
  Widget _buildBody() {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildFamilyMembersBar(),
          _buildFunctionalModules(),
          _buildFamilyActivities(),
        ],
      ),
    );
  }
  
  // 构建家庭成员栏
  Widget _buildFamilyMembersBar() {
    // 模拟数据
    final members = [
      {'name': '爸爸', 'avatar': Icons.face},
      {'name': '妈妈', 'avatar': Icons.face_3},
      {'name': '儿子', 'avatar': Icons.face_2},
      {'name': '女儿', 'avatar': Icons.face_4},
    ];
    
    return Container(
      padding: EdgeInsets.symmetric(vertical: 16.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '家庭成员',
                  style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
                ),
                TextButton(
                  onPressed: () => Navigator.pushNamed(context, AppRouter.family),
                  child: const Text('查看全部'),
                ),
              ],
            ),
          ),
          SizedBox(height: 8.h),
          SizedBox(
            height: 80.h,
            child: ListView(
              scrollDirection: Axis.horizontal,
              padding: EdgeInsets.symmetric(horizontal: 8.w),
              children: [
                ...members.map((member) => _buildMemberAvatar(member)),
                _buildAddMemberButton(),
              ],
            ),
          ),
        ],
      ),
    );
  }
  
  // 构建成员头像
  Widget _buildMemberAvatar(Map<String, dynamic> member) {
    return InkWell(
      onTap: () => Navigator.pushNamed(context, AppRouter.family),
      child: Container(
        width: 70.w,
        margin: EdgeInsets.symmetric(horizontal: 8.w),
        child: Column(
          children: [
            CircleAvatar(
              radius: 25.r,
              backgroundColor: AppTheme.primaryColor.withOpacity(0.2),
              child: Icon(
                member['avatar'] as IconData,
                color: AppTheme.primaryColor,
                size: 30.r,
              ),
            ),
            SizedBox(height: 4.h),
            Text(
              member['name'] as String,
              style: TextStyle(fontSize: 12.sp),
              textAlign: TextAlign.center,
              overflow: TextOverflow.ellipsis,
            ),
          ],
        ),
      ),
    );
  }
  
  // 构建添加成员按钮
  Widget _buildAddMemberButton() {
    return InkWell(
      onTap: () => Navigator.pushNamed(context, AppRouter.family),
      child: Container(
        width: 70.w,
        margin: EdgeInsets.symmetric(horizontal: 8.w),
        child: Column(
          children: [
            CircleAvatar(
              radius: 25.r,
              backgroundColor: Colors.grey.withOpacity(0.2),
              child: Icon(
                Icons.add,
                color: Colors.grey,
                size: 30.r,
              ),
            ),
            SizedBox(height: 4.h),
            Text(
              '添加',
              style: TextStyle(fontSize: 12.sp, color: Colors.grey),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }
  
  // 构建功能模块
  Widget _buildFunctionalModules() {
    return Container(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '功能模块',
            style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 16.h),
          GridView.count(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            crossAxisCount: 3,
            mainAxisSpacing: 16.h,
            crossAxisSpacing: 16.w,
            children: [
              _buildModuleCard(
                icon: Icons.photo_album,
                title: '相册',
                color: Colors.blue,
                onTap: () => _navigateTo(const GalleryScreen()),
              ),
              _buildModuleCard(
                icon: Icons.account_balance_wallet,
                title: '财务管理',
                color: Colors.green,
                onTap: () => _navigateTo(const finance_home.HomeScreen()),
              ),
              _buildModuleCard(
                icon: Icons.lock,
                title: '安全保险箱',
                color: Colors.orange,
                onTap: () => _navigateTo(const SecureVaultScreen()),
              ),
              _buildModuleCard(
                icon: Icons.calendar_today,
                title: '家庭日历',
                color: Colors.purple,
                onTap: () => _navigateTo(const CalendarScreen()),
              ),
              _buildModuleCard(
                icon: Icons.favorite,
                title: '关爱管理',
                color: Colors.red,
                onTap: () => _showFeatureUnderDevelopment('关爱管理'),
              ),
              _buildModuleCard(
                icon: Icons.description,
                title: '文档管理',
                color: Colors.teal,
                onTap: () => _showFeatureUnderDevelopment('文档管理'),
              ),
              _buildModuleCard(
                icon: Icons.location_on,
                title: '位置共享',
                color: Colors.amber,
                onTap: () => _showFeatureUnderDevelopment('位置共享'),
              ),
              _buildModuleCard(
                icon: Icons.people,
                title: '家庭成员',
                color: Colors.indigo,
                onTap: () => Navigator.pushNamed(context, AppRouter.family),
              ),
              _buildModuleCard(
                icon: Icons.add,
                title: '添加功能模块',
                color: Colors.grey,
                onTap: () => _showFeatureUnderDevelopment('添加功能模块'),
              ),
            ],
          ),
        ],
      ),
    );
  }
  
  // 构建功能模块卡片
  Widget _buildModuleCard({
    required IconData icon,
    required String title,
    required VoidCallback onTap,
    required Color color,
  }) {
    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.r)),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(16.r),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircleAvatar(
              radius: 25.r,
              backgroundColor: color.withOpacity(0.2),
              child: Icon(
                icon,
                size: 30.r,
                color: color,
              ),
            ),
            SizedBox(height: 8.h),
            Text(
              title,
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
      ),
    );
  }
  
  // 构建家庭活动
  Widget _buildFamilyActivities() {
    // 模拟数据
    final activities = [
      {'title': '爸爸的生日', 'date': '4月 20日', 'icon': Icons.cake},
      {'title': '家庭聚会', 'date': '4月 25日', 'icon': Icons.receipt},
      {'title': '家庭旅行', 'date': '5月 1日', 'icon': Icons.flight},
    ];
    
    return Container(
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '家庭活动',
            style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 16.h),
          ...activities.map((activity) => _buildActivityItem(activity)),
        ],
      ),
    );
  }
  
  // 构建活动项
  Widget _buildActivityItem(Map<String, dynamic> activity) {
    return Card(
      margin: EdgeInsets.only(bottom: 12.h),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.r)),
      child: ListTile(
        leading: CircleAvatar(
          backgroundColor: AppTheme.primaryColor.withOpacity(0.2),
          child: Icon(
            activity['icon'] as IconData,
            color: AppTheme.primaryColor,
          ),
        ),
        title: Text(activity['title'] as String),
        subtitle: Text(activity['date'] as String),
        trailing: const Icon(Icons.arrow_forward_ios, size: 16),
        onTap: () => _showFeatureUnderDevelopment(activity['title'] as String),
      ),
    );
  }
  
  // 跳转到页面
  void _navigateTo(Widget screen) {
    Navigator.of(context).push(
      MaterialPageRoute(builder: (context) => screen),
    );
  }
  
  // 显示功能开发中
  void _showFeatureUnderDevelopment(String feature) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text('$feature 功能开发中')),
    );
  }
  
  // 显示退出登录确认对话框
  void _showLogoutConfirmDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('退出登录'),
        content: const Text('确定要退出登录吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () => _logout(context),
            child: const Text('确定'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
          ),
        ],
      ),
    );
  }
  
  // 退出登录
  Future<void> _logout(BuildContext context) async {
    try {
      // 显示加载指示器
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(
          child: CircularProgressIndicator(),
        ),
      );
      
      // 清除认证状态
      await ref.read(authStateProvider.notifier).logout();
      
      // 清除家庭数据
      ref.read(familyProvider.notifier).clearData();
      
      // 清除其他缓存数据
      await _clearLocalCache();
      
      // 关闭加载指示器
      Navigator.pop(context);
      
      // 关闭抽屉
      Navigator.pop(context);
      
      // 跳转到登录页面
      Navigator.pushNamedAndRemoveUntil(
        context, 
        AppRouter.login, 
        (route) => false,
      );
    } catch (e) {
      // 关闭加载指示器
      Navigator.pop(context);
      
      // 显示错误提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('退出登录失败: $e')),
      );
    }
  }
  
  // 清除本地缓存
  Future<void> _clearLocalCache() async {
    try {
      // 清除用户盒子
      final userBox = Hive.box(AppConstants.userBox);
      await userBox.clear();
      
      // 清除家庭盒子
      final familyBox = Hive.box(AppConstants.familyBox);
      await familyBox.clear();
      
      // 清除日历盒子
      final calendarBox = Hive.box(AppConstants.calendarBox);
      await calendarBox.clear();
      
      // 清除其他盒子（根据需要添加）
      // 例如：相册、财务等
    } catch (e) {
      debugPrint('清除本地缓存失败: $e');
    }
  }
}
